var axios = require('axios');
var common = require('../utils/sha512');
let http = axios.create({
  timeout: 20000, //延时
});
http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
http.defaults.headers.get['Content-Type'] = 'application/json; charset=utf-8';
http.interceptors.request.use( //请求参数设置
  config => {
    var timestamp = new Date().format("yyyy-MM-dd hh");
    var param = JSON.stringify({});
    if (config.method === 'post') {
      if ((typeof config.data) == 'string') {
        var data = JSON.parse(config.data);
        param = JSON.stringify(data);
      } else if ((typeof config.data) == 'object') {
        param = JSON.stringify(config.data);
      };
      var sign = common.hexsha512(param + timestamp);
      config.data = "param=" + param + "&sign=" + sign;  //1字符串拼接
    } else if (config.method === 'get') {
      if ((typeof config.params) == 'string') {
        var param = JSON.parse(config.params);
        param = JSON.stringify(param);
      } else if ((typeof config.params) == 'object') {
        var param = JSON.stringify(config.params);
      }
      var sign = common.hexsha512(param + timestamp);
      config.params = {
        param: param,
        sign: sign
      }
    };
    return config;
  },
  err => {
    return Promise.reject(err)
  })

http.interceptors.response.use( //响应请求
  config => {
    return config
  },
  err => {
    return Promise.reject(err)
  })

module.exports = http;